package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SkillBookPop;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JiChaProgressActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView img;
    private EditText edit;
    private BaseRVAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ping_lun);
        img = (RecyclerView) findViewById(R.id.img);
        edit = (EditText) findViewById(R.id.edit);

        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        if (1 == getIntent().getIntExtra("pinglun", 0)) {
            title.setText("评论");
        } else {
            title.setText("发布动态");
        }
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("发布");
        submit.setVisibility(View.VISIBLE);
        submit.setOnClickListener(this);

        img.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        list.add("add");
        adapter = new BaseRVAdapter(this, list) {

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_photo;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                if ("add".equals(list.get(position))) {
                    holder.getView(R.id.cha).setVisibility(View.GONE);
                    holder.getImageView(R.id.img).setImageResource(R.drawable.mq_ic_add_img);
                    holder.getImageView(R.id.img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPopmenu(v);
                        }
                    });
                } else {
                    holder.getImageView(R.id.img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(JiChaProgressActivity.this, ShowImageDetail.class);
                            intent.putStringArrayListExtra("paths", (ArrayList<String>) list);
                            intent.putExtra("index", position);
                            startActivity(intent);
                        }
                    });
                    holder.getView(R.id.cha).setVisibility(View.VISIBLE);

                    x.image().bind(holder.getImageView(R.id.img), list.get(position));

                    holder.getView(R.id.cha).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            list.remove(position);
                            if (list.size() != 0) {
                                if (!"add".equals(list.get(list.size() - 1))) {
                                    list.add("add");
                                }
                            }
                            notifyDataSetChanged();
                        }
                    });
                }
            }

        };
        img.setAdapter(adapter);
    }

    /**
     * ------头像点击
     */
    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code
    private File tempFile;

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + "a.jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };
    private String imageName = "b.jpg";// 原图名称

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    String imagePath = AlbumImagePath.getPath(this, uri);
                    System.out.println("imagePath**====www==" + imagePath);
                    updateImage(imagePath, uri);
                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);
                    String imagePath = tempFile.getAbsolutePath();
                    File file = new File(imagePath);
                    if (!file.exists()) {
                        return;
                    }
                    updateImage(imagePath, uri);
                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;


            default:
                break;
        }

    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }
        //  x.image().bind(iv_edit_head, "file://" + imagePath, options);

        if (list.size() < 9) {
            list.add(list.size() - 1, imagePath);
            adapter.notifyDataSetChanged();
        } else {
            list.add(list.size() - 1, imagePath);
            list.remove(list.size() - 1);
            adapter.notifyDataSetChanged();
        }
        Log.e("img", list.size() + "");
    }

    private List<String> list = new ArrayList<>();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                if (edit.getText().toString().trim().equals("") && list.size() == 1) {
                    MyToast("请输入内容");
                    return;
                }
                upLoad();
                break;
        }
    }

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", getIntent().getStringExtra("orderid"));
        if (!"".equals(edit.getText()))
            map.put("content", edit.getText().toString());
        map.put("address", "");
        if (list.size() != 1) {
            for (int h = 0; h < list.size(); h++) {
                if (!"add".equals(list.get(h))) {
                    String compressImage = BitnapUtils.compressImage(list.get(h), list.get(h), 30);
                    File compressedPic = new File(compressImage);
                    map.put("list" + (h + 1), compressedPic);
                }
            }
        }

        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.DECORATE_ADDAUDITDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });


    }
}
